package com.graduation.check.service.impl;

import com.graduation.check.dto.*;
import com.graduation.check.entity.User;
import com.graduation.check.mapper.TeacherStudentMapper;
import com.graduation.check.mapper.UserMapper;
import com.graduation.check.service.TeacherStudentService;
import com.graduation.check.utils.TypeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TeacherStudentServiceImpl implements TeacherStudentService {
    
    @Autowired
    private TeacherStudentMapper teacherStudentMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public StudentListResponse getStudentList(StudentListRequest request) {
        log.info("开始获取学生列表 - page: {}, size: {}", request.getPage(), request.getSize());
        try {
            // 计算offset
            int offset = (request.getPage() - 1) * request.getSize();
            request.setPage(offset);
        
        // 查询学生列表
        List<StudentListItem> records = teacherStudentMapper.selectStudentList(request);
        
        // 查询总数
        Long total = teacherStudentMapper.countStudents(request);
        
        // 查询统计信息
        Map<String, Object> summary = teacherStudentMapper.getStudentSummary(request);
        
        // 组装响应
        StudentListResponse response = new StudentListResponse();
        response.setTotal(total);
        response.setPage(request.getPage() / request.getSize() + 1);
        response.setSize(request.getSize());
        response.setTotalPages((int) Math.ceil((double) total / request.getSize()));
        response.setRecords(records);
        
        // 设置统计信息（安全转换Long/BigDecimal到Integer）
        StudentListResponse.SummaryStats stats = new StudentListResponse.SummaryStats();
        stats.setTotalStudents(TypeConverter.getIntValue(summary, "totalStudents"));
        stats.setActiveStudents(TypeConverter.getIntValue(summary, "activeStudents"));
        stats.setInactiveStudents(TypeConverter.getIntValue(summary, "inactiveStudents"));
        stats.setTotalSubmissions(TypeConverter.getIntValue(summary, "totalSubmissions"));
        response.setSummary(stats);
        
        log.info("学生列表获取成功 - total: {}", total);
        return response;
        } catch (Exception e) {
            log.error("获取学生列表失败", e);
            throw new RuntimeException("获取学生列表失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public Map<String, Object> getStudentsByClass(String major) {
        List<Map<String, Object>> students = teacherStudentMapper.selectStudentsByClass(major);
        
        // 按班级分组
        Map<String, List<Map<String, Object>>> groupedByClass = students.stream()
            .collect(Collectors.groupingBy(s -> (String) s.get("className")));
        
        Map<String, Object> result = new LinkedHashMap<>();
        
        for (Map.Entry<String, List<Map<String, Object>>> entry : groupedByClass.entrySet()) {
            String className = entry.getKey();
            List<Map<String, Object>> classStudents = entry.getValue();
            
            Map<String, Object> classData = new HashMap<>();
            classData.put("students", classStudents);
            
            // 计算班级统计（安全转换类型）
            Map<String, Object> classStats = new HashMap<>();
            classStats.put("totalStudents", classStudents.size());
            classStats.put("activeStudents", classStudents.stream()
                .filter(s -> {
                    Object status = s.get("status");
                    return status != null && ((Number) status).intValue() == 1;
                }).count());
            classStats.put("totalSubmissions", classStudents.stream()
                .mapToLong(s -> {
                    Object count = s.getOrDefault("submissionCount", 0);
                    return count instanceof Number ? ((Number) count).longValue() : 0L;
                }).sum());
            classStats.put("avgSubmissions", classStudents.stream()
                .mapToLong(s -> {
                    Object count = s.getOrDefault("submissionCount", 0);
                    return count instanceof Number ? ((Number) count).longValue() : 0L;
                }).average().orElse(0.0));
            
            classData.put("classStats", classStats);
            result.put(className, classData);
        }
        
        return result;
    }
    
    @Override
    @Transactional
    public User addStudent(AddStudentRequest request) {
        // 检查账号是否已存在
        User existingUser = userMapper.findByAccount(request.getAccount());
        if (existingUser != null) {
            throw new RuntimeException("学号已存在");
        }
        
        // 检查邮箱是否已存在
        User existingEmail = userMapper.findByEmail(request.getEmail());
        if (existingEmail != null) {
            throw new RuntimeException("邮箱已存在");
        }
        
        // 创建新学生
        User user = new User();
        user.setAccount(request.getAccount());
        user.setName(request.getName());
        user.setEmail(request.getEmail());
        user.setPassword(request.getPassword()); // 实际应该加密
        user.setUserType("S");
        user.setMajor(request.getMajor());
        user.setClassName(request.getClassName());
        user.setStatus(1); // 1表示启用/正常状态
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        userMapper.insert(user);
        return user;
    }
    
    @Override
    @Transactional
    public User updateStudent(Long studentId, UpdateStudentRequest request) {
        User user = userMapper.findById(studentId);
        if (user == null) {
            throw new RuntimeException("学生不存在");
        }
        
        if (request.getName() != null) {
            user.setName(request.getName());
        }
        if (request.getEmail() != null) {
            user.setEmail(request.getEmail());
        }
        if (request.getMajor() != null) {
            user.setMajor(request.getMajor());
        }
        if (request.getClassName() != null) {
            user.setClassName(request.getClassName());
        }
        if (request.getStatus() != null) {
            user.setStatus(request.getStatus());
        }
        
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
        
        return user;
    }
    
    @Override
    @Transactional
    public void deleteStudent(Long studentId) {
        User user = userMapper.findById(studentId);
        if (user == null) {
            throw new RuntimeException("学生不存在");
        }
        
        // 真正删除
        userMapper.deleteById(studentId);
    }
    
    @Override
    @Transactional
    public Map<String, Object> batchDeleteStudents(List<Long> studentIds) {
        int successCount = 0;
        int failCount = 0;
        List<Long> successIds = new ArrayList<>();
        List<Map<String, Object>> failDetails = new ArrayList<>();
        
        for (Long studentId : studentIds) {
            try {
                deleteStudent(studentId);
                successCount++;
                successIds.add(studentId);
            } catch (Exception e) {
                failCount++;
                Map<String, Object> fail = new HashMap<>();
                fail.put("studentId", studentId);
                fail.put("reason", e.getMessage());
                failDetails.add(fail);
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalCount", studentIds.size());
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("successIds", successIds);
        result.put("failDetails", failDetails);
        result.put("deleteTime", LocalDateTime.now());
        
        return result;
    }
    
    @Override
    @Transactional
    public Map<String, Object> batchImportStudents(MultipartFile file) {
        int successCount = 0;
        int failCount = 0;
        int updateCount = 0;
        int createCount = 0;
        List<Map<String, Object>> successDetails = new ArrayList<>();
        List<Map<String, Object>> failDetails = new ArrayList<>();
        
        try {
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                throw new RuntimeException("文件名为空");
            }
            
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(file.getInputStream(), "UTF-8")
            );
            
            String line;
            int lineNum = 0;
            boolean isFirstLine = true;
            
            while ((line = reader.readLine()) != null) {
                lineNum++;
                
                // 跳过第一行（表头）
                if (isFirstLine) {
                    isFirstLine = false;
                    continue;
                }
                
                // 跳过空行
                if (line.trim().isEmpty()) {
                    continue;
                }
                
                try {
                    // 解析CSV行
                    String[] values = line.split(",");
                    
                    if (values.length < 5) {
                        failCount++;
                        Map<String, Object> fail = new HashMap<>();
                        fail.put("row", lineNum);
                        fail.put("account", "");
                        fail.put("reason", "数据格式不完整");
                        failDetails.add(fail);
                        continue;
                    }
                    
                    String account = values[0].trim();
                    String name = values[1].trim();
                    String email = values[2].trim();
                    String major = values[3].trim();
                    String className = values[4].trim();
                    
                    // 数据验证
                    if (account.isEmpty() || name.isEmpty() || email.isEmpty()) {
                        failCount++;
                        Map<String, Object> fail = new HashMap<>();
                        fail.put("row", lineNum);
                        fail.put("account", account);
                        fail.put("reason", "必填字段不能为空");
                        failDetails.add(fail);
                        continue;
                    }
                    
                    // 检查用户是否存在
                    User existingUser = userMapper.findByAccount(account);
                    
                    if (existingUser != null) {
                        // 更新现有用户
                        existingUser.setName(name);
                        existingUser.setEmail(email);
                        existingUser.setMajor(major);
                        existingUser.setClassName(className);
                        existingUser.setUpdateTime(LocalDateTime.now());
                        userMapper.update(existingUser);
                        
                        updateCount++;
                        successCount++;
                        
                        Map<String, Object> success = new HashMap<>();
                        success.put("row", lineNum);
                        success.put("account", account);
                        success.put("message", "更新成功");
                        successDetails.add(success);
                    } else {
                        // 创建新用户
                        User user = new User();
                        user.setAccount(account);
                        user.setName(name);
                        user.setEmail(email);
                        user.setPassword("123456"); // 默认密码
                        user.setUserType("S");
                        user.setMajor(major);
                        user.setClassName(className);
                        user.setStatus(1); // 1表示启用/正常状态
                        user.setCreateTime(LocalDateTime.now());
                        user.setUpdateTime(LocalDateTime.now());
                        
                        userMapper.insert(user);
                        
                        createCount++;
                        successCount++;
                        
                        Map<String, Object> success = new HashMap<>();
                        success.put("row", lineNum);
                        success.put("account", account);
                        success.put("message", "创建成功");
                        successDetails.add(success);
                    }
                    
                } catch (Exception e) {
                    failCount++;
                    Map<String, Object> fail = new HashMap<>();
                    fail.put("row", lineNum);
                    fail.put("account", "");
                    fail.put("reason", e.getMessage());
                    failDetails.add(fail);
                }
            }
            
            reader.close();
            
        } catch (Exception e) {
            throw new RuntimeException("文件解析失败：" + e.getMessage());
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalCount", successCount + failCount);
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("updateCount", updateCount);
        result.put("createCount", createCount);
        result.put("successDetails", successDetails);
        result.put("failDetails", failDetails);
        result.put("importTime", LocalDateTime.now());
        
        return result;
    }
    
    @Override
    public String exportStudentList(StudentListRequest request) {
        // 实现导出功能
        // 这里应该生成真实的Excel文件并返回文件路径或直接返回文件流
        // 为简化实现，我们返回一个标识符，前端可以根据这个标识符下载文件
        return "student_export_" + System.currentTimeMillis() + ".xlsx";
    }
}
